<?php

namespace App\Listeners;

use App\Events\CommentCreated;
use App\Models\FormId;
use App\Models\UserThirdPartyBind;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use EasyWeChat\Factory;

class SendWeixinTemplateMessageToUserWhenCreateComment
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  CommentCreated  $event
     * @return void
     */
    public function handle(CommentCreated $event)
    {
        $comment = $event->comment;
        $parentComment = $comment->parentComment;
        $logPrefix = sprintf("%s, comment: %s", __METHOD__, $comment->id);
        if (!$parentComment) {
            \Log::info(sprintf("%s, comment has no parent comment", $logPrefix));
            return;
        }

        $thirdPartyBind = UserThirdPartyBind::platformWeixinOpen()->where('uid', $parentComment->uid)->first();
        if (!$thirdPartyBind) {
            \Log::info(sprintf("%s, parent comment user: %s has no bind weixin", $logPrefix, $parentComment->uid));
            return;
        }
        $formId = FormId::where('uid', $parentComment->uid)->where('openid', $thirdPartyBind->openid)->first();
        if (!$formId) {
            \Log::info(sprintf("%s, parent comment user: %s(%s) has no formId", $logPrefix, $parentComment->uid, $thirdPartyBind->openid));
            return;
        }

        $miniApp = \EasyWechat::miniProgram();
        if ($parentComment->root_id) {
            $rootComment = $parentComment->rootComment;
        } else {
            $rootComment = $parentComment;
        }

        $page = sprintf('/pages/comment-detail/comment-detail?root_comment_key=%s&include_root_comment=1&append_key=%s', $rootComment->key, $comment->key);
        $data = [
            'touser' => $thirdPartyBind->openid,
            'template_id' => 'U5hrMfhIai9MgGlosxxVXnvkPoeZN4WP_tCxacbcLB8',
            'page' => $page,
            'form_id' => $formId['form_id'],
            'data' => [
                'keyword1' => $parentComment->detail_excerpt,
                'keyword2' => $comment->detail_excerpt,
                'keyword3' => $comment->user->name,
                'keyword4' => $comment->created_at->format('Y-m-d H:i:s'),

            ],
        ];
        $result = $miniApp->template_message->send($data);
        \Log::info(sprintf("%s, send data: %s, result: %s", $logPrefix, json_encode($data, 336), json_encode($result, 336)));
    }
}
